package com.yesun.task.pipeline.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * spring实现多数据源选择，继承AbstractRoutingDataSource
 * spring的application.properties中配置多个数据源，然后@Configration中将多个数据源bean加载到ioc
 */
public class DynamicDataSourceRoute extends AbstractRoutingDataSource {

    protected final Logger log = LoggerFactory.getLogger(getClass());
    private List<String> listDataSource = new ArrayList<String>();

    //DataSource数量
    private int dataSourceCount = 1; //默认一个
    public int getDataSourceCount() {
        return dataSourceCount;
    }
    public void setDataSourceCount(int dataSourceCount) {
        this.dataSourceCount = dataSourceCount;
    }
    public String getDataSource(int index) {
        return listDataSource.get(index);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DBContextHolder.getDbType();
    }
    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        //这里就有了数据源数量了
        log.debug("加载数据源数量:" + targetDataSources.size());
        this.setDataSourceCount(targetDataSources.size());
        for (Map.Entry entry : targetDataSources.entrySet()) {
            Object lookupKey = resolveSpecifiedLookupKey(entry.getKey());
            DataSource dataSource = resolveSpecifiedDataSource(entry.getValue());
            listDataSource.add(lookupKey.toString());
        }
    }

}
